import Snake, { snakes } from './sanke.js';
import Bug, { bugs } from './bug.js';

export default class Play {
  // 动画方向
  direction;
  timer;
  constructor(app) {
    this.$app = app;
    this.bindDocument();
  }

  play() {
    if (this.timer) return;
    this.timer = setInterval(this.run.bind(this), this.$app.$options.speed);
  }

  // 移动处理
  run() {
    snakes.reduce((position, snake) => {
      // 设置蛇新的坐标
      snake.left = position.left;
      snake.top = position.top;
      return snake.oldPosition;
    }, this.position());

    this.crashBug();
    this.crashCanvas();
  }

  // 检测蛇头是否和虫子相撞
  crashBug() {
    if (Snake.left === Bug.left && Snake.top === Bug.top) {
      this.$app.snake({
        left: snakes[snakes.length - 1].oldPosition.left,
        top: snakes[snakes.length - 1].oldPosition.top,
        bgColor: 'red',
      });
      Bug.remove();
      this.$app.bug();
    }
  }

  // 检测小蛇是否和画布碰撞
  crashCanvas() {
    const { box } = this.$app.$options;
    // 获取小蛇头的位置
    const { left, top } = snakes[0];
    if (
      left < 0 ||
      top < 0 ||
      left > this.$app.$options.width - box.width ||
      top > this.$app.$options.height - box.height
    ) {
      clearInterval(this.timer);
      alert('Game Over！');
    }
  }

  bindDocument() {
    document.addEventListener('keydown', (e) => {
      this.direction = e.key.substr(5).toLowerCase();
      this.play();
    });
  }

  // 获取到蛇头移动新位置
  position() {
    const position = { left: Snake.left, top: Snake.top };
    const { box } = this.$app.$options;
    switch (this.direction) {
      case 'up':
        position.top = Snake.top - box.width;
        break;
      case 'down':
        position.top = Snake.top + box.width;
        break;
      case 'left':
        position.left = Snake.left - box.width;
        break;
      case 'right':
        position.left = Snake.left + box.width;
        break;
    }
    return position;
  }
}
